package com.zlz.blog.server.config.login;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.zlz.blog.manage.common.enums.ResultCodeEnum;
import com.zlz.blog.manage.common.response.ResultSet;
import com.zlz.blog.server.util.LoginUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;

/**
 * @author wb_zhulinzhong
 * @date 2021-05-19 17:04:52
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private final LoginUtil loginUtil;

    public LoginHandlerInterceptor(LoginUtil loginUtil) {
        this.loginUtil = loginUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();
        ServletOutputStream outputStream = response.getOutputStream();

        // 白名单放行（无需登录，无需鉴权）
        if (loginUtil.checkPath(requestUrl)) {
            return true;
        }

        // 检查是否登录
        ResultSet<Boolean> booleanResultSet = loginUtil.checkLogin(request);
        if (!ResultCodeEnum.SUCCESS.getCode().equals(booleanResultSet.getCode())) {
            writeResp(outputStream, ResultSet.loginError(booleanResultSet.getMessage()));
            return false;
        }

        // 鉴权
        ResultSet<Boolean> resultSet = loginUtil.checkAuthorization(requestUrl);
        if (!ResultSet.isSuccess(resultSet)) {
            writeResp(outputStream, resultSet);
            return false;
        }
        loginUtil.refresh(request);
        return true;
    }

    private void writeResp(ServletOutputStream outputStream, ResultSet<Boolean> resultSet) throws IOException {
        String notLogin = new JSONObject(resultSet).toString();
        outputStream.write(notLogin.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
